<?php

namespace Caifenglei\AuthRbac\Http\Actions;

use Caifenglei\AuthRbac\Models\Permission;
use Caifenglei\AuthRbac\Models\Role;
use Illuminate\Contracts\Database\Eloquent\Builder;
use Illuminate\Support\Arr;

class RoleAction
{
    /**
     * @param $data: name, status, permissions(ids, names)
     * @return \Spatie\Permission\Contracts\Role|\Spatie\Permission\Models\Role
     */
    public static function createRole($data) {

        $role = Role::create([
            'name' => $data['name'],
//            'guard_name' => 'api',
            'label' => Arr::get($data, 'label', $data['name']),
            'status' => $data['status'],
            'sort' => Arr::get($data, 'sort', 0),
        ]);

        if($permissions = Arr::get($data, 'permissions')) {
            if(is_numeric($permissions[0])){
                $permissions = Permission::whereIn('id', $permissions)->pluck('name');
            }
            $role->givePermissionTo($permissions);
        }

        return $role;
    }

    /**
     * 更新角色
     */
    public static function updateRole($role, $data) {

        $attrs = Arr::except($data, ['permissions', 'users']);
        if(!empty($attrs)){
            $name = $data['name'];
            $role->update([
                'name' => $name,
                'label' => Arr::get($data, 'label', $name),
                'status' => $data['status'],
                'sort' => Arr::get($data, 'sort', 0),
            ]);
        }

        //角色权限更新
        $permissions = Arr::get($data, 'permissions');
        if(!is_null($permissions)) {
            if(count($permissions) > 0){
                if(is_numeric($permissions[0])){
                    $permissions = Permission::whereIn('id', $permissions)->pluck('name');
                }
                $role->syncPermissions($permissions);
            }else {
                $role->syncPermissions([]);
            }
        }

        //角色用户更新
        $users = Arr::get($data, 'users');
        if(!is_null($users)) {
            $role->users()->sync($users);
        }

        return $role;
    }

    /**
     * 删除未赋予用户的角色
     * @param $roles
     * @return array
     */
    public static function deleteRoles($roles) {
        $deleted_role_ids = [];
        foreach ($roles as $role){
            if($role->users_count === 0){
                $deleted_role_ids[] = $role->id;
                $role->delete();
            }
        }
        return $deleted_role_ids;
    }

    /**
     * 获取角色详情
     */
    public static function getRoleInfo($roleId){
        $role = Role::with(['permissions' => function(Builder $query){
            $query->select(config('auth-rbac.role_permission_fields'))->orderBy('sort');
        }, 'users' => function(Builder $query){
            $query->select(config('auth-rbac.role_user_fields'));
        }])->find($roleId);

        if($role){
            $parents_id = $role->permissions->pluck('parent_id')->unique()->toArray();
            foreach($role->permissions as &$perm){
                $perm->is_leaf = in_array($perm->id, $parents_id) ? 0 : 1;
            }
        }

        return $role;
    }
}
